package com.boss.salary.tasks;

import com.boss.common.util.DateUtils;
import com.boss.salary.constant.SystemDictConstant;
import com.boss.salary.dao.IPersonExtDao;
import com.boss.salary.dao.IPersonInfoDao;
import com.boss.salary.dao.IPersonOperateDao;
import com.boss.salary.dao.ISalaryMonthEndDao;
import com.boss.salary.entity.AgencyVerify;
import com.boss.salary.entity.PersonExt;
import com.boss.salary.entity.PersonInfo;
import com.boss.salary.entity.PersonOperate;
import com.boss.salary.service.IAgencyVerifyService;
import com.boss.sys.utils.SysUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <br>Title: 按照人员生效时间更新人员信息
 * <br>Description: 按照人员生效时间更新人员信息
 * <br>Author: 王再岐
 * <br>Date: 2020-11-14 10：31
 */
@Component
//@EnableScheduling
public class PersonStartDataTasks {
    /**
     * 引入日志框架常量
     */
    private final static Logger logger = LoggerFactory.getLogger(PersonStartDataTasks.class);

    private static DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    @Autowired
    private IPersonOperateDao iPersonOperateDao;

    @Autowired
    private IPersonInfoDao iPersonInfoDao;

    @Autowired
    private IPersonExtDao iPersonExtDao;

    @Autowired
    private ISalaryMonthEndDao iSalaryMonthEndDao;

    @Autowired
    private IAgencyVerifyService iAgencyVerifyService;

    /**
     * 当生效时间小于等于当前时间时，将数据更新到人员表，变为正式数据，并更新操作表生效状态
     * 每天晚上1点执行
     */
//    @Scheduled(cron = "0 0 1 * * ?")
    public void getPersonByStartDate() throws ParseException {
        logger.info("===开始检查未生效的人员数据====");
        // 获取所有审核通过，并且未生效的数据
        List<PersonOperate> operateList = iPersonOperateDao.getPersonNotReal();
        if (!StringUtils.isEmpty(operateList) && operateList.size() > 0) {
            Map<String, String> map = getAgencyInfo();
            for (PersonOperate personOperate : operateList) {
                String agencyId = personOperate.getAgencyId();
                String verityCode = map.get(agencyId);
                // 如果单位未审核，则更新数据
                if (!String.valueOf(SystemDictConstant.IS_TRUE).equals(verityCode)) {
                    // 获取生效日期
                    String startDate = personOperate.getStartDate();
                    Date date = df.parse(startDate);
                    ZoneId zoneId = ZoneId.systemDefault();
                    LocalDateTime localDateTime = LocalDateTime.ofInstant(date.toInstant(), zoneId);
                    // 如果当前时间大于等于生效日期，则更新人员表数据
                    if (!localDateTime.isAfter(LocalDateTime.now())) {
                        updatePerson(personOperate);
                    }
                }
            }
        }
        logger.info("===结束检查未生效的人员数据====");
    }


    /**
     * 获取所有单位的单位审核状态
     * @return
     */
    private Map<String, String> getAgencyInfo() {
        Map<String, String> map = new HashMap<>(200);
        List<AgencyVerify> list = iAgencyVerifyService.getAgencyVerifyInfo();
        if (!StringUtils.isEmpty(list) && list.size() > 0) {
            for (AgencyVerify agencyVerify : list) {
                map.put(agencyVerify.getAgencyId(), agencyVerify.getSalaryVerifiedInAgencyCode());
            }
        }
        return map;
    }

    /**
     * 更新人员表数据
     */
    private void updatePerson(PersonOperate personOperate) {
        // 将操作表中的数据修改为已通过审核
        personOperate.setIdenIsVerify(String.valueOf(SystemDictConstant.IS_FALSE));
        personOperate.setUpdateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
        personOperate.setVerifyState(SystemDictConstant.IS_AUDIT);
        personOperate.setIsReal(SystemDictConstant.IS_TRUE);
        iPersonOperateDao.updatePersonOperate(personOperate);
        // 更新人员表数据
        PersonInfo personInfo = new PersonInfo();
        personInfo.setId(personOperate.getPersonId());
        personInfo.setCreateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
        personInfo.setUpdateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
        personInfo.setPersonName(personOperate.getPersonName());
        personInfo.setSexCode(personOperate.getSexCode());
        personInfo.setIdenTypeCode(personOperate.getIdenTypeCode());
        personInfo.setNation(personOperate.getNation());
        personInfo.setNatCode(personOperate.getNatCode());
        personInfo.setState(personOperate.getState());
        personInfo.setBirthday(personOperate.getBirthday());
        personInfo.setWorkInitDate(personOperate.getWorkInitDate());
        personInfo.setFundmode(personOperate.getFundmode());
        personInfo.setIsDeleted(SystemDictConstant.IS_FALSE);
        PersonExt personExt = new PersonExt(personOperate);
        personExt.setCreateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
        personExt.setUpdateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
        personExt.setIsDeleted(SystemDictConstant.IS_FALSE);
        // 如何是新增人，将操作表数据添加到人员信息表
        if (SystemDictConstant.ADD_PERSON.equals(personOperate.getOperateCode())) {
            personExt.setIsStopSalary(SystemDictConstant.IS_FALSE);
            personExt.setId(SysUtils.generateGuid());
            personInfo.setIdenNo(personOperate.getIdenNo());
            iPersonInfoDao.savePersonInfo(personInfo);
            iPersonExtDao.savePersonExt(personExt);
            // 单位审核表增加离休人数
            if (SystemDictConstant.QUIT_PERSON.equals(personOperate.getState())) {
                iAgencyVerifyService.updateAddQuitPersonNum(personOperate.getAgencyId());
            }
            // 单位审核表增加在职人数
            else if (SystemDictConstant.REGISTER_PERSON.equals(personOperate.getState())) {
                iAgencyVerifyService.updateAddPersonNum(personOperate.getAgencyId());
            }
            // 工资表增加人员数据
            Object[] params = new Object[] {
                    SysUtils.generateGuid(), String.valueOf(DateUtils.getCurrentTimeStamp()),
                    String.valueOf(DateUtils.getCurrentTimeStamp()), personOperate.getAgencyId(),
                    personOperate.getPersonId(), SystemDictConstant.IS_FALSE
            };
            iSalaryMonthEndDao.addPersonSalary(params);
        }
        // 如果是调出，在操作表添加去向单位数据，并更新人员信息表数据
        else if (SystemDictConstant.OUT_PERSON.equals(personOperate.getOperateCode())) {
            // 更新操作表调出数据为已审核通过
            personOperate.setVerifyState(SystemDictConstant.IS_AUDIT);
            iPersonOperateDao.updatePersonOperate(personOperate);
            String agencyId = personOperate.getAgencyId();
            // 保存操作表数据
            String outAgencyId = personOperate.getOutToAgency();
            personOperate.setId(SysUtils.generateGuid());
            personOperate.setAgencyId(outAgencyId);
            personOperate.setDeptId(null);
            personOperate.setOutToAgency(null);
            personOperate.setOperateCode(SystemDictConstant.IN_PERSON);
            personOperate.setVerifyState(null);
            personOperate.setIsDeleted(SystemDictConstant.IS_FALSE);
            personOperate.setCreateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
            personOperate.setUpdateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
            iPersonOperateDao.savePersonOperate(personOperate);
            // 将原有的人员信息标记删除
            iPersonInfoDao.deletePersonInfo(personOperate.getPersonId());
            personExt.setIsDeleted(SystemDictConstant.IS_TRUE);
            iPersonExtDao.updatePersonExt(personExt);
            // 单位审核表减人数
            iAgencyVerifyService.updateDeletePersonNum(agencyId);
            // 删除工资表数据
            iSalaryMonthEndDao.deletePersonSalary(personOperate.getPersonId());
        }
        // 如果是消减，将人员表标记删除
        else if (SystemDictConstant.DELETE_PERSON.equals(personOperate.getOperateCode())) {
            personInfo.setIsDeleted(SystemDictConstant.IS_TRUE);
            iPersonInfoDao.deletePersonInfo(personOperate.getPersonId());
            personExt.setIsDeleted(SystemDictConstant.IS_TRUE);
            iPersonExtDao.updatePersonExt(personExt);
            // 单位审核表减人数
            iAgencyVerifyService.updateDeletePersonNum(personOperate.getAgencyId());
            // 删除工资表数据
            iSalaryMonthEndDao.deletePersonSalary(personOperate.getPersonId());
        }
        // 如果是调入，将人员表数据的单位信息更新为调入单位的id
        else if (SystemDictConstant.IN_PERSON.equals(personOperate.getOperateCode())) {
            // 更新人员表数据
            personInfo.setIsDeleted(SystemDictConstant.IS_FALSE);
            iPersonInfoDao.updatePersonInfo(personInfo);
            // 更新人员拓展表数据
            String outAgencyId = personOperate.getAgencyId();
            personExt.setDeptId(null);
            personExt.setAgencyId(outAgencyId);
            personExt.setAgencyCode(null);
            personExt.setVerifyState(SystemDictConstant.NO_SUBMIT);
            personExt.setIsStopSalary(SystemDictConstant.IS_FALSE);
            personExt.setIsDeleted(SystemDictConstant.IS_FALSE);
            iPersonExtDao.updatePersonExt(personExt);
            // 修改工资表人的单位id
            iSalaryMonthEndDao.updateAgencyIdByPersonId(personOperate.getPersonId(), personOperate.getAgencyId(),
                    String.valueOf(DateUtils.getCurrentTimeStamp()));
            // 单位审核表加人数
            iAgencyVerifyService.updateAddPersonNum(personOperate.getAgencyId());
            // 工资表增加人员数据
            Object[] params = new Object[] {
                    SysUtils.generateGuid(), String.valueOf(DateUtils.getCurrentTimeStamp()),
                    String.valueOf(DateUtils.getCurrentTimeStamp()), personOperate.getAgencyId(),
                    personOperate.getPersonId(), SystemDictConstant.IS_FALSE
            };
            iSalaryMonthEndDao.addPersonSalary(params);
        }
        // 更新人员信息数据
        else {
            iPersonInfoDao.updatePersonInfo(personInfo);
            iPersonExtDao.updatePersonExt(personExt);
        }
    }
}
